<template>
    <van-popup v-model="show" position="bottom" round safe-area-inset-bottom closeable @closed="closePop">
        <div class="sku-box-wrap">
            <div class="sku-price">
                <img class="sku-head__img" :src="skuSelectImgs || skuMainImg" alt="">
                <div class="sku-head__content">
                    <div class="sku-head__content--price">
                        <div v-if="skuPrice > 0 || mainPrice > 0">
                            <span style="font-size: .28rem;">￥</span>{{ skuId ? skuPrice : mainPrice }}
                        </div>
                        <div class="hd_box" v-if="price_integral > 0 || mainIntegral > 0">
                            <span v-if="skuPrice > 0 || mainPrice > 0">+</span>
                            <div class="hd_text"><img src="../../../images/huaduo_icon.png" alt="">{{ skuId ?
                                price_integral : mainIntegral }}</div>
                        </div>
                    </div>
                    <div class="sku-head__content--stock">库存：{{ skuId ? skuStock : stock }}</div>
                    <!-- 显示贡献值 -->
                    <div class="good-info-num" v-if="currentContribution">
                        {{ currentContribution }}
                    </div>
                </div>
            </div>

            <!-- 规格展示 -->
            <div v-if="goodSpec" class="sku-list">
                <div v-for="(item, index) in goodSpec.attribute_list" :key="index" class="sku-list__li">
                    <div class="sku-list__li--name">{{ item.name }}</div>
                    <div class="sku-list__li--values clearfix">
                        <div v-for="(pItem, pIndex) in item.items" :key="pIndex" :class="[
                            'sku-list__li--values-item fl',
                            pItem.isShow ? '' : 'disable',
                            subIndex[index] == pIndex ? 'on' : '',
                        ]" @click="specificationBtn(pItem, index, pIndex)">{{ pItem.item }}</div>
                    </div>
                </div>
            </div>

            <!-- 步进器 -->
            <div class="sku-step">
                <span class="sku-step__label">数量</span>
                <van-stepper v-model="skuNum" :max="skuStock" />
            </div>

            <!-- 操作按钮 -->
            <div v-if="mode == 'cart'" class="confirm-btn active-btn" @click="handleToAddCart">确定</div>
            <div v-if="mode == 'buy'" class="confirm-btn active-btn" @click="handleToBuy">确定</div>

            <div v-if="!mode" class="btn-ul">
                <div class="btn-cart" @click="handleToAddCart">加入购物车</div>
                <div class="btn-buy" @click="handleToBuy">立即购买</div>
            </div>
        </div>
    </van-popup>
</template>

<script>
export default {
    props: {
        mode: {
            type: String,
            default: ''
        },
        stock: {
            type: Number,
            default: 0,
        },
        // 主价格
        mainPrice: {
            type: Number,
            default: 0,
        },
        // 主花朵
        mainIntegral: {
            type: Number,
            default: 0,
        },
        goodSpec: {
            type: Object,
            default: null
        },
        contribution: {
            type: String,
            default: null
        }
    },
    data() {
        return {
            show: false,
            selectArr: [], // 存放被选中的值
            shopItemInfo: {}, // 存放要和选中的值进行匹配的数据
            subIndex: [], // 是否选中,这里定义数组来判断
            skuNum: 1, // yi xuan
            skuId: '',
            skuAttr: '', // 已选规格属性
            skuStock: Number.MAX_SAFE_INTEGER, // 选中库存
            skuPrice: '', // 选中规格的价钱
            price_integral: '',
            skuSelectImgs: '', // 已选图片
            currentContribution: '', // 当前选中的贡献值
        }
    },

    computed: {
        skuMainImg() {
            // sku图片
            if (!this.goodSpec) {
                return ''
            }
            return this.goodSpec.cover_url;
        },
    },
    methods: {
        closePop() {
            this.show = false;
        },
        init() {
            // 修改数据结构格式，改成键值对的方式，以方便和选中之后的值进行匹配
            const skuList = this.goodSpec.spec_list;

            for (const i in skuList) {
                const keyValue = skuList[i].spec_key;
                this.shopItemInfo[keyValue] = skuList[i];
            }

            this.checkItem();
        },
        wordToLowerCase(data) {
            //sku规格大小写兼容处理，字母统一转小写，方便比对,小数点，中括号也要去除,不然报错
            let str = String(data).toLowerCase();
            let newstr = str.replace(/\./g, '点').replace(/\[/g, '【').replace(/\]/g, '】');
            newstr = newstr.replace(/\、/g, '点')
            newstr = newstr.replace(/\（/g, '左括')
            newstr = newstr.replace(/\）/g, '右括')
            newstr = newstr.substring(0, 20);

            console.log(newstr.replace(/\s+/g, ''), '000')
            return newstr.replace(/\s+/g, '');
        },
        isMay(result) {
            for (const i in result) {
                if (result[i] == '') {
                    return true; // 如果数组里有为空的值，那直接返回true
                }
            }

            const resultStr = result.join("_");
            return !(!(this.shopItemInfo[resultStr] && this.shopItemInfo[resultStr].store_count) || this.shopItemInfo[resultStr].store_count === '0');
        },
        // sku点击
        specificationBtn(pItem, index, pIndex) {
            // 禁选
            if (!pItem.isShow) {
                return;
            }

            if (this.selectArr[index] !== pItem.id) {
                this.selectArr[index] = pItem.id;
                this.subIndex[index] = pIndex;
            } else {
                this.selectArr[index] = '';
                this.subIndex[index] = -1; // 去掉选中的颜色

                // 清除
                this.skuPrice = '';
                this.price_integral = ''
                this.skuStock = Number.MAX_SAFE_INTEGER;
                this.skuId = '';
                this.skuSelectImgs = '';
                this.currentContribution = ''; // 清除贡献值
            }

            // 规格属性
            this.skuAttr = this.selectArr.join(' ');

            // 外层显示 - 暂不要
            // this.$emit('skuAttrListen', this.skuAttr);

            this.checkItem();
        },
        checkItem() {
            const option = this.goodSpec.attribute_list;
            const result = []; // 定义数组储存被选中的值
            for (var i in option) {
                result[i] = this.selectArr[i] ? this.selectArr[i] : '';
            }

            for (var i in option) {
                const last = result[i]; // 把选中的值存放到字符串last去
                for (const k in option[i].items) {
                    result[i] = option[i].items[k].id; // 赋值，存在直接覆盖，不存在往里面添加name值

                    option[i].items[k].isShow = this.isMay(result); // 在数据里面添加字段isShow来判断是否可以选择
                }

                result[i] = last; // 还原，目的是记录点下去那个值，避免下一次执行循环时被覆盖
            }

            const resultStr = result.join("_");
            if (this.shopItemInfo[resultStr]) {
                this.skuPrice = this.shopItemInfo[resultStr].price || '';
                this.price_integral = this.shopItemInfo[resultStr].price_integral || '';
                this.skuStock = this.shopItemInfo[resultStr].store_count;
                this.skuId = this.shopItemInfo[resultStr].id;
                this.skuSelectImgs = this.shopItemInfo[resultStr].image_url;
                
                // 获取贡献值信息
                this.getContributionValue(this.shopItemInfo[resultStr]);
            } else {
                this.currentContribution = ''; // 没有匹配的规格时清除贡献值
            }

            this.$forceUpdate();
        },
        // 获取贡献值
        getContributionValue(specInfo) {
            // 安全判断：确保labels存在且不为空数组
            if (specInfo && 
                specInfo.labels && 
                Array.isArray(specInfo.labels) && 
                specInfo.labels.length > 0 &&
                specInfo.labels[0] &&
                specInfo.labels[0].name) {
                
                this.currentContribution = specInfo.labels[0].name;
            } else {
                this.currentContribution = ''; // 没有贡献值时设为空
            }
        },
        // 加入购物车
        handleToAddCart() {
            if (!this.skuId) {
                this.$toast('请先选择规格')
                return;
            }

            this.$emit('addCart', {
                quantity: this.skuNum,
                spec_id: this.skuId
            })
        },
        // 立即购买
        handleToBuy() {
            if (!this.skuId) {
                this.$toast('请先选择规格')
                return;
            }

            this.$emit('toBuy', {
                quantity: this.skuNum,
                spec_id: this.skuId
            })
        }
    }
}
</script>
<style lang="scss">
.sku-box-wrap {
    width: 7.5rem;

    .sku-price {
        display: flex;
        padding: 0.4rem 0.32rem;

        .sku-head__img {
            width: 1.8rem;
            height: 1.8rem;
            border-radius: 0.16rem;
        }

        .sku-head__content {
            margin-left: 0.24rem;

            .sku-head__content--price {
                height: 0.56rem;
                margin-bottom: 0.12rem;
                // line-height: 0.56rem;
                font-size: 0.4rem;
                font-weight: 500;
                color: #31A653;
                display: flex;
                align-items: center;
                // justify-content: center;

                .hd_box {
                    display: flex;

                    span {
                        font-size: .28rem;
                        height: .32rem;
                        line-height: .3rem;
                        color: #31A653;
                        margin-left: .04rem;
                        margin-right: .04rem;
                    }

                    img {
                        width: .32rem;
                        height: .32rem;
                        vertical-align: middle;
                        margin-right: .03rem;
                    }

                    .hd_text {
                        font-size: .32rem;
                        height: .32rem;
                        color: #31A653;
                        display: flex;
                        align-items: center;
                        justify-content: center;

                    }
                }

                // &::before {
                //     content: '¥';
                //     font-size: 0.24rem;
                // }
            }

            .sku-head__content--stock {
                height: 0.34rem;
                line-height: 0.34rem;
                font-size: 0.24rem;
                font-weight: 400;
                color: #999999;
            }

            .good-info-num {
                display: flex;
                justify-content: center;
                height: .36rem;
                margin-top: .30rem;
                align-items: center;
                border-radius: .06rem;
                border: 1px solid #31A653;
                font-family: PingFangSC, PingFang SC;
                font-weight: 400;
                font-size: .22rem;
                padding: .04rem .12rem;
                color: #31A653;
            }
        }
    }

    .sku-list {
        max-height: 4.3rem;
        overflow-y: auto;

        &::-webkit-scrollbar {
            display: none;
        }

        &::-webkit-scrollbar-track {
            display: none;
        }

        &::-webkit-slider-thumb {
            display: none;
        }

        .sku-list__li {
            margin-bottom: 0.28rem;
            padding: 0 0.32rem;

            .sku-list__li--name {
                // height: 0.4rem;
                margin-bottom: 0.24rem;
                line-height: 0.4rem;
                font-weight: 400;
                font-size: 0.28rem;
                color: #333333;
            }

            .sku-list__li--values {
                .sku-list__li--values-item {
                    max-width: 7.02rem;
                    height: 0.56rem;
                    padding: 0 0.28rem;
                    color: #333333;
                    font-weight: 400;
                    font-size: 0.24rem;
                    text-align: center;
                    line-height: 0.56rem;
                    background: #F4F4F4;
                    border-radius: 0.28rem;
                    border: 1px solid #F4F4F4;
                    margin-right: 0.32rem;
                    margin-bottom: 0.28rem;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    word-break: break-all;
                    box-sizing: border-box;

                    &.on {
                        color: #31A653;
                        background: #ECF9EE;
                    }

                    &.disable {
                        color: #cccccc;
                    }
                }
            }

        }
    }

    .sku-step {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 0.44rem;
        padding: 0.1rem 0.32rem 0.64rem;

        .sku-step__label {
            font-weight: 400;
            font-size: 0.28rem;
            color: #333333;
        }

        .van-stepper {
            .van-stepper__minus {
                width: 22px;
                height: 22px;
                border-radius: 50%;
            }

            .van-stepper__plus {
                width: 22px;
                height: 22px;
                border-radius: 50%;
            }

            .van-stepper__input {
                background: #ffffff;
            }
        }
    }

    .confirm-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 7.02rem;
        height: 0.88rem;
        margin: auto;
        margin-bottom: 0.24rem;
        font-size: 0.32rem;
        font-weight: 500;
        color: #ffffff;
        background: linear-gradient(90deg, #75BE70 0%, #56AE48 100%);
        border-radius: 0.44rem;
    }

    .btn-ul {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 0.24rem;
        margin-bottom: 0.24rem;

        .btn-cart {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 3.4rem;
            height: 0.88rem;
            font-size: 0.32rem;
            font-weight: 500;
            color: #ffffff;
            background: #FFB900;
            border-radius: 0.44rem;
        }

        .btn-buy {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 3.4rem;
            height: 0.88rem;
            font-size: 0.32rem;
            font-weight: 500;
            color: #ffffff;
            background: linear-gradient(90deg, #75BE70 0%, #56AE48 100%);
            border-radius: 0.44rem;
        }
    }
}
</style>